// https://www.lintcode.com/problem/binary-tree-zigzag-level-order-traversal/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        // write your code here
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        List<TreeNode> nodes = new ArrayList<>();
        nodes.add(root);
        boolean fr = true;
        while (nodes.size() > 0) {
            List<Integer> level = new ArrayList<>();
            List<TreeNode> nnodes = new ArrayList<>();
            for (TreeNode t : nodes) {
                level.add(t.val);
                if (fr) {
                    if (t.left != null) {
                        nnodes.add(t.left);
                    }
                    if (t.right != null) {
                        nnodes.add(t.right);
                    }
                } else {
                    if (t.right != null) {
                        nnodes.add(t.right);
                    }
                    if (t.left != null) {
                        nnodes.add(t.left);
                    }
                }
            }
            ret.add(level);
            nodes = nnodes;
            Collections.reverse(nodes);
            fr = !fr;
        }
        return ret;
    }
}